﻿using Gtkj.CMS.Models;
using SmartBusExt.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace Gtkj.CMS.Common
{
    /// <summary>
    /// 文件上传helper
    /// </summary>
    public class UploadHelper
    {
        SmartBusExtensionEntities db = new SmartBusExtensionEntities();
        public  string  Upload(string name,string FileName, byte[] FileData)
        {

            string year = DateTime.Now.Year.ToString();
            string month = DateTime.Now.Month.ToString();
            //获取当前时间
            string dt = year+"-"+month;
            //按日期动态创建目录
            string pt = HttpContext.Current.Server.MapPath("/Uploads/") + name+"\\"+dt + "\\";
            DirectoryInfo di = new DirectoryInfo(pt);
            //判断目录是否存在
            if (!di.Exists)
            {
                di.Create();

            }

            if (FileData.Length == 0)
            {
                return "";
            }
            //获取后缀名
            string exname = FileName.Substring(FileName.LastIndexOf("."));
            if (exname != ".jpg" && exname != ".png" && exname != ".gif" && exname != ".xls" && exname != ".xlsx")
            {
                return "fileError";
            }

            string filePath = "";
            string path = "";
            #region
            Random rnd = new Random();
            string timePath= DateTime.Now.ToString("yyyyMMddHHmmss") + rnd.Next(1000, 9999) + exname;
            filePath = "Uploads/" +name+"/"+dt+"/"+timePath;
            path = HttpContext.Current.Server.MapPath("~/" + filePath);

            try
            {
                //保存
                using (FileStream fstxt = new FileStream(path, FileMode.Create))
                {
                    fstxt.Write(FileData, 0, FileData.Length);
                }
                             
            }
            catch
            {
                return "uploadError";
            }
           
            #endregion

            return filePath;
        }
    }
}